<template>
    <div class='home-container'>
        <SideNav :openeds="openeds" :activeTab="activeTab"></SideNav>
        <div class='right-container'>
            <Header class="header" :headerList="headerList"></Header>
            <div class="right-content white-color">
                <div class="add-title">
                    <img src="../../src/assets/img/welcome/add.png" alt="">
                    <span>新增学生</span>
                </div>
                <div class="add-form-container">
                    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px" class="add-form">
                        <el-form-item label="手机号码" prop="phonenumber">
                            <el-input v-model="ruleForm.phonenumber" :disabled="$route.query.action === 'edit'"></el-input>
                        </el-form-item>
                        <el-form-item label="学生姓名" prop="fullname">
                            <el-input v-model="ruleForm.fullname" placeholder="请输入学生姓名"></el-input>
                        </el-form-item>
                        <el-form-item label="出生日期" prop="birthday">
                            <el-date-picker type="date" placeholder="选择日期" v-model="ruleForm.birthday" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width: 100%;">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="性别" prop="sex">
                            <el-select v-model="ruleForm.sex" placeholder="请选择">
                                <el-option label="男" value="1"></el-option>
                                <el-option label="女" value="2"></el-option>
                                <!--<el-option label="保密" value="3"></el-option>-->
                            </el-select>
                        </el-form-item>
                        <el-form-item label="备注" prop="desc">
                            <el-input type="textarea" v-model="ruleForm.desc"></el-input>
                        </el-form-item>
                        <el-form-item v-if="$route.query.action !== 'edit'" label="验证码" prop="rcode">
                            <el-input class="sure-code-input" v-model="ruleForm.rcode" placeholder="手机验证码">
                            </el-input>
                            <el-button class="get-code-btn" @click="sendMsg" :disabled="isDisabled">{{buttonName}}
                            </el-button>
                        </el-form-item>
                        <el-form-item class="btn-group">
                            <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
                            <el-button @click="$router.push('/studentList')">取消</el-button>
                        </el-form-item>
                    </el-form>
                </div>

            </div>
        </div>
    </div>
</template>

<script>
import Header from '../../src/components/Header'
import SideNav from '../../src/components/SideNav'
import {
    sendsms,
    getStudentDetail,
    addStudent,
    updateStudent
} from '@/api/studentList'
export default {
    name: 'home',
    data() {
        var validatePhone = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('手机号不能为空'))
            } else {
                const reg = /^1[34578]\d{9}$/
                if (reg.test(value)) {
                    callback()
                } else {
                    return callback(new Error('请输入正确的手机号'))
                }
            }
        }
        return {
            headerList: ['会员', '学生', '新增学生'],
            openeds: ['2', '2-1'],
            activeTab: 'Member',
            buttonName: '获取验证码',
            isDisabled: false,
            time: 60,
            resultArr: [],
            ruleForm: {
                fullname: '',
                phonenumber: '',
                rcode: '',
                birthday: '',
                sex: '',
                desc: ''
            },
            rules: {
                fullname: [{
                    required: true,
                    message: '请填写账号',
                    trigger: 'blur'
                }],
                phonenumber: [{
                    required: true,
                    validator: validatePhone,
                    trigger: 'blur'
                }],
                rcode: [{
                    required: true,
                    message: '请填写验证码',
                    trigger: 'blur'
                }],
                type: [{
                    required: true,
                    message: '请选择身份',
                    trigger: 'change'
                }],
                birthday: [{
                    required: true,
                    message: '请选择出生日期',
                    trigger: 'change'
                }],
                sex: [{
                    required: true,
                    message: '请选择性别',
                    trigger: 'change'
                }],
                desc: [{
                    required: true,
                    message: '请填写备注',
                    trigger: 'blur'
                }]
            },
            id: this.$route.query.id,
            action: this.$route.query.action,
            submitApi: this.$route.query.action === 'edit' ? updateStudent : addStudent,
            submitMsg: this.$route.query.action === 'edit' ? '编辑成功' : '添加成功'
        }
    },
    created() {
        if (this.$route.query.action === 'edit') {
            this.getDetail()
        } else {
            this.resetForm()
        }
    },
    methods: {
        getDetail() {
            getStudentDetail({
                student: this.id
            }).then(res => {
                if (res.code == 1) {
                    let data = res.data
                    this.ruleForm.fullname = data.realname
                    this.ruleForm.phonenumber = data.phone
                    this.ruleForm.birthday = data.birthday
                    this.ruleForm.sex = data.sex.toString()
                    this.ruleForm.desc = data.desc
                }
            })
        },
        async submitForm(formName) {
            let _self = this
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let data = {}
                    if (this.action === 'edit') {
                        data = {
                            student: _self.id,
                            fullname: _self.ruleForm.fullname,
                            birthday: _self.ruleForm.birthday,
                            sex: _self.ruleForm.sex,
                            desc: _self.ruleForm.desc
                        }
                    } else {
                        data = {
                            phonenumber: _self.ruleForm.phonenumber,
                            rcode: _self.ruleForm.rcode,
                            fullname: _self.ruleForm.fullname,
                            birthday: _self.ruleForm.birthday,
                            sex: _self.ruleForm.sex,
                            desc: _self.ruleForm.desc
                        }
                    }
                    this.submitApi(data).then(res => {
                        if (res.code == 1) {
                            _self.$message({
                                message: this.submitMsg,
                                type: 'success'
                            })
                            _self.$router.push({
                                path: '/studentList'
                            })
                        }
                    })
                } else {
                    return false
                }
            })
        },
        resetForm() {
            Object.keys(this.ruleForm).forEach(item => {
                this.ruleForm[item] = ''
            })
        },
        //封装验证函数
        checkForm(formName) {
            let _self = this
            let result = new Promise(function (resolve, reject) {
                _self.$refs.ruleForm.validateField([formName], valid => {
                    if (!valid) {
                        resolve()
                    } else {
                        // eslint-disable-next-line prefer-promise-reject-errors
                        reject()
                    }
                })
            })
            _self.resultArr.push(result) //push 得到promise的结果
        },
        async sendMsg() {
            let _self = this
            _self.resultArr = [];
            ['phonenumber'].forEach(item => { //根据表单的ref校验
                _self.checkForm(item)
            })
            //resultArr数组的值必须是promise对象才能使用Promise.all，在checkForm做了这一步
            Promise.all(_self.resultArr).then(function () { //都通过了
                console.log('所有表单验证通过')
                _self.isDisabled = true
                let interval = window.setInterval(function () {
                    _self.buttonName = _self.time + 's'
                    --_self.time
                    if (_self.time < 0) {
                        _self.buttonName = '重新发送'
                        _self.time = 60
                        _self.isDisabled = false
                        window.clearInterval(interval)
                    }
                }, 1000)
                sendsms({
                    'phonenumber': _self.ruleForm.phonenumber,
                    'code': _self.ruleForm.code
                }).then(res => {
                    if (res.code == 1) {
                        _self.$message({
                            message: res.message,
                            type: 'success'
                        })
                    }
                })
            }).catch(function () {
                // console.log("err");
            })
        }
    },
    components: {
        Header,
        SideNav
    }
}

</script>
<style lang="less" scoped>
    @import url('../../src/assets/less/Mixins.less');
    @import url('../../src/assets/less/common.less');

    html,
    body {
        height: 100%
    }

    .add-title {
        height: 70px;
        line-height: 70px;
        padding-left: 30px;

        img {
            height: 20px;
            width: 20px;
            position: relative;
            top: 4px;
            margin-right: 12px;
        }
    }

    .add-form-container {
        width: calc(100% - 60px);
        margin: auto;
        border: 1px solid rgba(221, 223, 230, 1);

        .add-form {
            width: 500px;
            margin: auto;
            margin-top: 30px;
        }

        .el-select {
            width: 100%
        }
    }
    .sure-code-input {
        width: 300px;
        color: rgba(170, 170, 170, 1);
        margin-left: 1px;
    }
    .sure-code {
        margin-left: 14px;
    }
    .get-code-btn {
        background: rgba(85, 168, 253, 1);
        border-radius: 2px;
        padding: 0px 14px;
        color: #fff;
        cursor: pointer;
        float: right;
        font-size: 14px;
        font-family: PingFang-SC-Regular;
        font-weight: 400;
        width: 97px;
        height: 39px;
    }
</style>
<style lang="less">
    .left-container {
        ul {
            background-color: #22345E
        }
    }

    .btn-group {
        >div {
            text-align: center
        }
    }

    .date-line {
        text-align: center !important
    }

    .add-title {
        height: 70px;
        line-height: 70px;
        padding-left: 30px;

        img {
            height: 20px;
            width: 20px;
            position: relative;
            top: 4px;
            margin-right: 12px;
        }

        span {
            font-size: 20px;
            font-family: PingFang-SC-Regular;
            font-weight: 400;
        }
    }

    // 下拉选
    .el-select-dropdown__item.hover,
    .el-select-dropdown__item:hover {
        background-color: #55a8fd !important;
        color: #ffffff !important;
    }

    .el-select-dropdown__list {
        padding-top: 0px !important;
        padding-bottom: 0px !important;
        font-size: 14px !important;
        font-family: PingFang-SC-Regular !important;
        font-weight: 400;
    }

    .popper__arrow {
        display: none !important;
    }

    // 日历
    .el-picker-panel__body {
        font-family: PingFang-SC-Regular !important;
    }

    @import url('../../src/assets/less/override-element-ui.less');

</style>
